package lwf.web.struts.action;


import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lwf.handler.IProcessHandler;
import lwf.handler.ProcessHandler;
import lwf.handler.entities.Score;
import lwf.web.struts.action.form.math.ArithmaticsActionForm;

import net.lwf.common.constant.ICommonConstant;
import net.lwf.entity.UserPreferences;
import net.lwf.number.util.RandomNumberGenerator;
import net.lwf.web.constant.IWebConstant;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


//public class WorkSheetAction extends DispatchAction {
public class WorkSheetAction extends BaseAction {
	
	//private static final Logger logger = Logger.getLogger(worksheet.struts.action.WorkSheetAction.class);
	
	public ActionForward checkanswer(ActionMapping mapping, 
			                         ActionForm form,
									 HttpServletRequest request, 
									 HttpServletResponse response)
			throws Exception {


		//String useranswer = request.getParameter("useranswer");
		String useranswer = getUserAnswer(request);
		ProcessHandler sumdetails = getSumData(request);
		PrintWriter out = response.getWriter();
		
		int apprimage = RandomNumberGenerator.generate(1,12);
		String imagetag = "<img src=\"" + request.getContextPath() + "/image/appreciation/not ok " + String.valueOf(apprimage) + ".gif\">&nbsp;&nbsp;";
		String answermsg = "<font color=\"red\"> Your answer is wrong.... Please try again.</font>";
		if(sumdetails.isMaxAttempts()) {
			answermsg = "<font color=\"red\"> You have reached maximum number of attempts to answer this sum. <br>" +
					    "You may click next for the next sum OR click Score to see the score.</font>";
			imagetag = "";
		}
		else {
			if (sumdetails.isCorrect(useranswer)) {
				answermsg = "<font color=\"blue\"> The answer is correct. You did it. </font>";
				imagetag = "<img src=\"" + request.getContextPath() + "/image/appreciation/ok " + String.valueOf(apprimage) + ".gif\">&nbsp;&nbsp;";
				response.setContentType("text/html");
			}
			if(!displayAppreiciation(request)) {
				answermsg = "<font color=\"blue\"> Your answer is recorded. You may click next for the next sum OR click Score to see the score</font>";
				imagetag = "";
			}			
		}
		this.resetLastData(request, sumdetails);
		out.println(imagetag + answermsg);
		out.flush();
		
		return null; // Not forwarding to anywhere, response is fully-cooked		

	}	
	
	public ActionForward score(ActionMapping mapping, 
			                   ActionForm form,
							   HttpServletRequest request, 
							   HttpServletResponse response)
			throws Exception {

		ArithmaticsActionForm soform = (ArithmaticsActionForm) form;
		Map mapsumdata = (HashMap) request.getSession().getAttribute(IWebConstant.SUMDATA);
		if(mapsumdata != null && mapsumdata.size() != 0) {
			Score score = new Score(mapsumdata);
			soform.setScore(score);			
		}
		else {
			soform.setDisplayScore(false);
		}


		return mapping.findForward("scores");

	}	
	
	public ActionForward clear(ActionMapping mapping, 
			                   ActionForm form,
			                   HttpServletRequest request, 
							   HttpServletResponse response)
			throws Exception {
		//request.setAttribute("username", getUserPreferences(request).getName());
		request.getSession().removeAttribute("sumdata");
		//request.getSession().invalidate();

		return mapping.findForward("success");

	}
	
/*	public ActionForward signoff(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String userid = getUser(request).getUserId();
		logger.debug("===================> User: " + userid + " logged OFF successfully at " + (new Date()).toString());
		request.setAttribute("username", userid);
		request.getSession().removeAttribute("sumdata");
		request.getSession().invalidate();
		
		return mapping.findForward("thankyou");

	}*/

	public void setSumData(HttpServletRequest request, ProcessHandler sumdetails) {
		HttpSession session = request.getSession();
		Map mapsumdata = null;
		int counter = 0;
		if (session.getAttribute(IWebConstant.SUMDATA) == null) {
			mapsumdata = new HashMap();
			counter = 1;
		} else {
			mapsumdata = (HashMap) session.getAttribute(IWebConstant.SUMDATA);
			counter = mapsumdata.size() + 1;
		}
		sumdetails.setStarttime(new java.util.Date().getTime());
		sumdetails.setQuestionNum(String.valueOf(counter));
		sumdetails.setUserAttemptLimit(getUserPreferences(request).getAttempts());
		mapsumdata.put(String.valueOf(counter), sumdetails);
		session.setAttribute(IWebConstant.SUMDATA, mapsumdata);
	}

	public ProcessHandler getSumData(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Map mapsumdata = (HashMap) session.getAttribute(IWebConstant.SUMDATA);
		int key = mapsumdata.size();
		ProcessHandler lastsumdetails = (ProcessHandler) mapsumdata.get(String.valueOf(key));
		return lastsumdetails;
	}

	public void resetLastData(HttpServletRequest request, ProcessHandler sumdetails) {
		sumdetails.setEndtime(new java.util.Date().getTime());
		HttpSession session = request.getSession();
		Map mapsumdata = (HashMap) session.getAttribute(IWebConstant.SUMDATA);
		int key = mapsumdata.size();
		mapsumdata.put(String.valueOf(key), sumdetails);
		session.setAttribute(IWebConstant.SUMDATA, mapsumdata);
	}
	
	private boolean displayAppreiciation(HttpServletRequest request) {
		UserPreferences userpref = getUserPreferences(request);
		if(userpref.getSeeAnswer().equals(ICommonConstant.YES)) {
			return true;
		}
		return false;
	}
	
	private UserPreferences getUserPreferences(HttpServletRequest request) {
		return getWebUser(request).getPreferences();
	}
	
	protected String getUserAnswer(HttpServletRequest request) {
		return request.getParameter("useranswer");
	}

	@Override
	public IProcessHandler getHandler(HttpServletRequest request) {
		return null;
	}

	@Override
	public String getPageTitle() {
		return null;
	}

	@Override
	public String getMainTitle() {
		return null;
	}

	@Override
	public String getPdfLink() {
		return null;
	}

	@Override
	public String getQuizLink() {
		return null;
	}
	
} //WorkSheetAction
